// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // 计算用户的上传的数据
  let arr = event.daarr;
  let sum = 0;
  let arrdata = []
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    sum += item.num * item.price;
    arrdata.push(item.id)
  }
  //查询数据看积分是否一样
  let user = await db.collection('users').where({
    _id: event.id
  }).get()
  console.log(user);
  console.log(event);
  if (user.data[0].jf == event.jf) {
    //商品减去库存
    let brr = [];
    for (let i = 0; i < event.daarr.length; i++) {
      let item = event.daarr[i];
      //商品添加到用户数据库
      if (item.num == 1) {
        brr.push(item);
      } else {
        for (let j = 0; j < item.num; j++) {
          await db.collection(user.data[0].gouwuche).add({
            data: {
              id: item.id,
              kucun: item.kucun,
              name: item.name,
              num: 1,
              price: item.price,
              text: item.text,
              checked: true,
              df: true,
            }
          }).then(res => {
            console.log("ck:===>", res);
          })
        }
      }
    }
    if (brr.length > 0) {
      for (let i = 0; i < brr.length; i++) {
        let item = brr[i]
        await db.collection(user.data[0].gouwuche).add({
          data: {
            id: item.id,
            kucun: item.kucun,
            name: item.name,
            num: item.num,
            price: item.price,
            text: item.text,
            checked: true,
            df: true,
          }
        }).then(res => {
          console.log("ck:===>", res);
        })
      }
    }
    //用户积分减去
    let str = `购买卡片，消费${sum}积分`
    let time = formatDate(new Date());
    let onj = {
      nr: str,
      time: time
    }
    console.log(user.data[0]);
    let arrayy = user.data[0].jfmingxi
    if (arrayy.length > 50) {
      arrayy = arrayy.slice(0, 50)
    }
    arrayy.unshift(onj)
    db.collection('users').doc(event.id).update({
      data: {
        // 表示指示数据库将字段自增 10
        jf: db.command.inc(-sum),
        jfmingxi: arrayy
      },
      success: function (res) {
        console.log(res.data)
      }
    })
    //返回成功
    return {
      code: 200,
      msg: true
    }
  } else {
    return {
      data: user.data[0],
      code: 400,
      msg: false
    }
  }
}


//时间格式化2023-01-01 00:00:00
function formatDate(date) {
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}